//index.js
//获取应用实例
var util = require('../../utils/util.js');
var activity_js = require('../../utils/activity.js');
const date = new Date();
const time = util.formatTime(date);
const nowadays = util.formatDate(date);
var app = getApp();
Page({
  data: {
    organizations: [],//发布身份列表
    organization: 0,//当前身份信息
    orgs_name: [],//发布身份名称列表
    repeattypes: ["仅一次", "每天", "每周", "隔周", "每月"],
    repeatcounts: ["once", "daily", "weekly", "fortnightly", "monthly"],
    address: "选择地址",
    joinable: 0,
    organization: '',
    starttime: time,
    startdate: nowadays,
    endtime: time,
    enddate: nowadays,
    nowaday: nowadays,
    repeatenddate: nowadays,
    repeatendtime: time,
    activity: false,
    is_repeat: false,
    picture: [],
    upload_pictures: [],
    activityIcon: " ../../image/mine-menu/right-arrow.png",
    repeattypeindex: 0,
    type: 1,
    owner: '',
    ownerid: 0,
    owner_list: [],
    owner_name_list: [],
    participants: 0,
    activity_create_type: 1,
    calendar_id: 0,
  },
  //事件处理函数

  onLoad: function (options) {
    console.log(options);
    var activity_create_type = options.activity_create_type;
    var calendar_id = options.calendar_id;
    if (calendar_id == undefined) {
      calendar_id = 0;
    }
    var type = options.type;
    var owner = options.owner;
    var that = this;
    var yuyue_session = wx.getStorageSync("yuyue_session");
    var joinable = 0;
    that.getOrganizations(yuyue_session);
    console.log(calendar_id)
    wx.setNavigationBarTitle({
      title: "发起活动",
    })
    this.setData({
      windowWidth: wx.getSystemInfoSync().windowWidth,
      picturewidth: (wx.getSystemInfoSync().windowWidth - 73) / 4,
      windowHeight: wx.getSystemInfoSync().windowHeight,
      pixelRatio: wx.getSystemInfoSync().pixelRatio,
      owner: wx.getStorageInfoSync("yuyue_session"),
      joinable: joinable,
      activity_create_type: activity_create_type, 
      calendar_id: calendar_id,
      type: type,
    })
    if (calendar_id != 0) {
      that.setData({
        owner: owner,
      });
    }
  },
  bindrepeattype: function (e) {
    var that = this;
    console.log(that.data.activity_create_type);
    if (that.data.activity_create_type == 1) {
      if (e.detail.value != 0) {
        wx.showModal({
          title: '重复活动请使用日历活动创建',
          content: '点击确认后，跳转到日历活动创建',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              wx.redirectTo({
                url: 'calendar',
              })
              return false;
            } else if (res.cancel) {
              console.log('用户点击取消')
              that.setData({
                repeattypeindex: 0
              })
              return false;
            }
          }
        })
      }
    }else {
      that.setData({
        is_repeat: true,
        repeattypeindex: e.detail.value
      })
      if (e.detail.value == 0) {
        that.setData({
          is_repeat: false
        })
      }
    }
  },

  //获取组织信息
  getOrganizations: function (yuyue_session) {
    var that = this;
    var orgs;
    var owner_list = [];
    var organizations = [];
    var orgs_name = [];
    var owner_name_list = [];
    wx.getUserInfo({
      success: function (res) {
        var userInfo = res.userInfo
        var nickName = userInfo.nickName
        var avatar = userInfo.avatarUrl
        var owner = new Object();
        owner.name = nickName;
        owner.avatar = avatar;
        owner.id = yuyue_session;
        owner.type = 1;
        owner_list.push(owner);
        owner_name_list.push(owner.name);
        
        util.organizations_request(function (data) {
          console.log(data);
          orgs = data;
          for (var org in orgs.own_orgs) {
            var owner = new Object();
            owner.name = orgs.own_orgs[org].name;
            owner.avatar = orgs.own_orgs[org].avatar_thumbnail_url;
            owner.id = orgs.own_orgs[org].id;
            owner.type = 2;
            owner_name_list.push(owner.name);
            owner_list.push(owner);
            
          } 
          for (var org in orgs.join_orgs) {
            var owner = new Object();
            owner.name = orgs.join_orgs[org].name;
            owner.avatar = orgs.join_orgs[org].avatar_thumbnail_url;
            owner.id = orgs.join_orgs[org].id;
            owner.type = 2;
            owner_name_list.push(owner.name);
            owner_list.push(owner);
          } 
          console.log(owner_list);
          console.log(owner_name_list);
          that.setData({
            owner_list: owner_list,
            owner_name_list: owner_name_list,
          });
        });
        return;
      }, fail(res) {
        util.neterror_Modal(function () {
          that.getOrganizations(yuyue_session);
          return;
        })
      }
    })
    //  console.log(organizations[0]);
  },

  //提交表单
  createActivity: function (e) {
    var that = this;
    var value = e.detail.value;
    
    var title = value.title;
    var content = value.content;
    var participants = value.participants ? value.participants : 0;
    var upload_pictures = that.data.upload_pictures;
    var images = [];
    for (var i in upload_pictures) {
      images.push(upload_pictures[i].upload_name);
    }
    var repeattypeindex = that.data.repeattypeindex;
    
    //var owner = that.data.owner;
    var address = that.data.address;
    var calendar_id = that.data.calendar_id;
    console.log(that.data.startdate);
    console.log(that.data.starttime);
    var begintime = util.formatTimeStamp(that.data.startdate, that.data.starttime) / 1000;
    var endtime = util.formatTimeStamp(that.data.enddate, that.data.endtime) / 1000;
    var repeatend = util.formatTimeStamp(that.data.repeatenddate, that.data.repeatendtime) / 1000;
    if (calendar_id == 0) {
      var ownerid = that.data.ownerid;
      var type = that.data.owner_list[ownerid].type;
      var owner = that.data.owner_list[ownerid].id;
    }else {
      var type = that.data.type;
      var owner = that.data.owner;
      if (type == 1) {
        var owner = wx.getStorageSync("yuyue_session");
      }
    }

    var joinable = that.data.joinable;
    var repeattype = that.data.repeatcounts[repeattypeindex];

    var joinsheet = [];
    if (value.needPhoneNum)
      joinsheet = [{
        title: "手机号",
        type: "text",
        choice: []
      }]
    if (value.needName)
      joinsheet.push({
        title: "姓名",
        type: "text",
        choice: []
      })
    if (value.needremarks)
      joinsheet.push({
        title: "备注",
        type: "text",
        choice: []
      })
    console.log("calendar_id:" + calendar_id);
    console.log("title:" + title);
    console.log("content:" + content);
    console.log(images);

    console.log("type:" + type); 
    console.log("owner:" + owner);

    console.log("address:" + address);
    console.log("begintime:" + begintime);
    console.log("endtime:" + endtime);
    console.log("repeattype:" + repeattype);

    console.log("joinable:" + joinable);
    console.log("participants:" + participants);
    console.log("repeatend:" + repeatend);
    console.log(joinsheet);
    //return false;
    wx.showModal({
      title: '是否确认提交？',
      content: '请注意，提交后无法修改',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定');
          //return false;
          var images = [];
          that.uploadDIY(upload_pictures, 0, 0, 0, upload_pictures.length, images, function (successUp, failUp, length, images){
            activity_js.organize(title, content, images, type, owner, address, begintime, endtime, repeattype, joinable, participants, repeatend, joinsheet, calendar_id);
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  addPicture: function (e) {
    var that = this;
    var upload_pictures = that.data.upload_pictures;
    wx.chooseImage({
      count: 9 - that.data.picNum,
      success: function (res) {
        var path = '';
        console.log(res);
        var imgs = res.tempFilePaths;
        for (var i in imgs) {
          upload_pictures.push(imgs[i]);
        }
        that.setData({
          picNum: upload_pictures.length,
          upload_pictures: upload_pictures
        })
        return false;
      }
    })
    this.setData({
      activity: e.detail.value
    })
  },
  bindPosition: function (e) {
    var that = this;
    var latitude = "";
    var longitude = '';
    var address = '';
    wx.chooseLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        address = res.address; 
        console.log("addr:" + latitude + longitude + address);
        that.setData({
          address: address
        })
        // wx.request({
        //     url: 'http://api.map.baidu.com/geocoder/v2/?ak=btsVVWf0TM1zUBEbzFz6QqWF&coordtype=gcj02ll&location=' + latitude + ',' + longitude + '&output=json&pois=0',
        // })
      },
      fail: function () {
        wx.showModal({
          title: '地点选择失败！请重试',
          showCancel: false
        })
      }
    })
  },
  removePicture: function (e) {
    //return false;
    var upload_name = e.target.dataset.upload_name;
    var upload_pictures = [];
    upload_pictures = this.data.upload_pictures;
    for (var i = 0; i < upload_pictures.length; i++) {
      if (upload_pictures[i] == upload_name) {
        upload_pictures.splice(i, 1);
        break;
      }
      console.log(upload_pictures[i]);
      console.log(i);
    }
    this.setData({
      upload_pictures: upload_pictures
    })

  },
  bindCreateActivity: function (e) {
    var that = this;
    var activity = !that.data.activity;
    console.log("createActivty ? :" + activity);
    this.setData({
      activity: activity,
      activityIcon: activity ? " ../../image/mine-menu/down-arrow.png" : " ../../image/mine-menu/right-arrow.png",
      repeattypeindex: 0,
      organization: that.data.nickName,
      starttime: time,
      startdate: nowadays,
      endtime: time,
      enddate: nowadays,
      address: "选择地址",
    })
  },
  bindStartDate: function (e) {
    this.setData({
      startdate: e.detail.value,
      enddate: e.detail.value
    })
  },
  bindStartTime: function (e) {
    this.setData({
      starttime: e.detail.value,
      //endtime: e.detail.value
    })
  },
  bindEnddate: function (e) {
    this.setData({
      enddate: e.detail.value
    })
  },
  bindEndTime: function (e) {
    this.setData({
      endtime: e.detail.value
    })
  },
  bindRepeatEndDate: function (e) {
    this.setData({
      repeatenddate: e.detail.value
    })
  },
  bindRepeatEndTime: function (e) {
    this.setData({
      repeatendtime: e.detail.value
    })
  },
  //选择身份
  chooseOrg: function (e) {
    var that = this;
    var owner_name_list = that.data.owner_name_list;
    wx.showActionSheet({
      itemList: owner_name_list,
      success: function (res) {
        that.setData({
          ownerid: res.tapIndex,
        })
      },
    })
  },
  navigateToTemplate: function (e) {
    wx.navigateTo({
      url: '../mine/template/index',
    })
  },
  
  //是否可加入
  joinClick: function (e){
    var that = this;
    var joinable = e.target.dataset.joinable;
    if (joinable == 1) {
      joinable = 0;
    } else if (joinable == 0) {
      joinable = 1;
    }
    that.setData({
      joinable: joinable
    });
  }, 
  uploadDIY(filePaths, successUp, failUp, i, length, images, callback) {
    if (filePaths.length == 0) {
      callback(0, 0, 0, []);
      return false;
    }
    wx.uploadFile({
      url: app.globalData.default_url + '/?action=api.v1.activity.upload_image',
      filePath: filePaths[i],
      name: 'file',
      success: (resp) => {
        successUp++;
      },
      fail: (res) => {
        failUp++;
      },
      complete: (res) => {
        var str = res.data;
        var json = JSON.parse(str); 
        i++;
        if (json.op == "upload_image") {
          images.push(json.data);
        }
        if (i == length) {
          console.log(images);
          callback(successUp, failUp, length, images);
          //this.showToast('总共' + successUp + '张上传成功,' + failUp + '张上传失败！');
        }
        else {  //递归调用uploadDIY函数
          this.uploadDIY(filePaths, successUp, failUp, i, length, images, callback);
        }
      },
    });
  },
})
